package com.example.demo.netty.h5;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @description:
 * @author: hhl
 * @createDate: 2023/12/22
 * @version: 1.0
 */
public class WriteServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        while(true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey next = iterator.next();
                iterator.remove();
                if(next.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey selectionKey = sc.register(selector, SelectionKey.OP_READ);
                    StringBuilder sb = new StringBuilder();
                    for(int i = 0;i<3000000;i++){
                       sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
                    int write = sc.write(buffer);
                    System.out.println("实际写入字节："+write);
                    if(buffer.hasRemaining()){
                        selectionKey.interestOps(selectionKey.interestOps()+SelectionKey.OP_WRITE);
                        selectionKey.attach(buffer);
                    }
                }else if(next.isWritable()){
                    ByteBuffer buffer = (ByteBuffer) next.attachment();
                    SocketChannel channel = (SocketChannel) next.channel();
                    int write = channel.write(buffer);
                    System.out.println("实际写入字节："+write);
                    if(!buffer.hasRemaining()){
                        next.interestOps(next.interestOps()-SelectionKey.OP_WRITE);
                        next.attach(null);
                    }
                }
            }
        }
    }
}
